package com.swss.g.assets.action;

import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.swss.g.assets.bean.Asset;
import com.swss.g.assets.bean.AssetSearch;
import com.swss.g.assets.bean.AstRange;
import com.swss.g.assets.service.AssetService;
import com.swss.g.base.BaseAction;
import com.swss.g.sys.service.ByglService;
import com.swss.g.sys.service.CurrentPeriodService;
import com.swss.g.sys.service.SysService;
import com.swss.g.user.bean.Role;
import com.swss.g.user.bean.User;
import com.swss.g.user.service.UserService;
import com.swss.util.BeanUtils;
import com.swss.util.Excel;
import com.swss.util.FileHelper;
import com.swss.util.Files;
import com.swss.util.Pagination;

public class AssetAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3016348148306946228L;
	protected String date;
	protected List<?> fundSubList;
	protected List<?> useDirList;
	protected List<?> nowStatusList;
	protected List<?> astSourceList;
	protected List<?> chargeOffDeptList;
	protected List<?> byglList;
	protected List<?> zjfsList;
	protected List<?> financeUserList;

	// 资产列表
	protected List<?> astList;

	// 上传图片
	protected File[] pics;
	protected String[] picFileNames;
	protected String[] picContentTypes;
	// 删除图片
	protected String delPic;

	// 上传发票
	protected File bill;
	protected String billFileName;
	protected String billContentTypes;
	// 资产类型
	protected char astType;
	protected Integer printType; // excel传值参数 1.asset 2.changeasset

	// 查询类别
	protected Integer searchType;
	// 条件session 是否清空
	protected String auditNoArray;
	// 查询菜单或条件查询标记
	protected Integer clearbean;
	// 资产修改标记 0.登记管理 1.未审修改 2.终审修改 3....
	protected Integer stamp;
	// 高级查询hql
	protected String hql;

	/**
	 * bean
	 */

	protected User user;

	protected Pagination<?> pagination;

	protected Role role;

	protected Asset asset;

	private AstRange astRange;

	/**
	 * service
	 * 
	 * @return
	 */
	protected AssetService assetService;
	protected CurrentPeriodService currentPeriodService;
	protected UserService userService;
	protected SysService sysService;
	protected ByglService gbyglService;

	/**
	 * 新增前页面准备
	 * 
	 * @return
	 */
	public String si() {
		try {
			user = this.getSessionAttr("user", User.class);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.format(new Date());

			fundSubList = this.getSysService().getFundSub();
			useDirList = this.getSysService().getUseDir();
			nowStatusList = this.getSysService().getNowStatus();
			astSourceList = this.getSysService().getAstSource();
			chargeOffDeptList = this.getSysService().getChargeOffDept();
			byglList = this.getGbyglService().findAllStandField();
			zjfsList = this.getSysService().getZheJiuFangShi();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "saveInit";
	}

	public String save() {

		try {
			String realPath = this.getRealPath("");
			if (picFileNames != null) {
				asset.setPicUrl1(FileHelper.saveFiles(pics, picFileNames,
						realPath));
			}
			if (billFileName != null) {
				asset.setPicUrl2(FileHelper.saveFile(bill, billFileName,
						realPath));
			}
			asset.setAstMark("S");
			// 设置单据号
			if (asset.getDanJuNo() == null || asset.getDanJuNo().equals("")) {
				asset.setDanJuNo(this.currentPeriodService
						.getBillNo(this.astType));
			}
			this.assetService.addAsset(asset);
			this
					.print("{\"code\":0,\"billNo\":\"" + asset.getDanJuNo()
							+ "\"}");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询单一资产准备
	 * 
	 * @return
	 */
	public String searchOneAst() {

		try {
			fundSubList = this.getSysService().getFundSub();
			useDirList = this.getSysService().getUseDir();
			nowStatusList = this.getSysService().getNowStatus();
			astSourceList = this.getSysService().getAstSource();
			chargeOffDeptList = this.getSysService().getChargeOffDept();
			byglList = this.getGbyglService().findAllStandField();
			zjfsList = this.getSysService().getZheJiuFangShi();

			asset = (Asset) this.assetService.findOneById(asset.getId());
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return "searchShow";
	}

	// 修改前准备
	public String modBefore() {
		try {

			fundSubList = this.getSysService().getFundSub();
			useDirList = this.getSysService().getUseDir();
			nowStatusList = this.getSysService().getNowStatus();
			astSourceList = this.getSysService().getAstSource();
			chargeOffDeptList = this.getSysService().getChargeOffDept();
			byglList = this.getGbyglService().findAllStandField();
			zjfsList = this.getSysService().getZheJiuFangShi();
			stamp = Integer.parseInt(this.getRequest().getParameter("stamp"));

			asset = this.assetService.findOneById(asset.getId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "modShow";
	}

	// 修改数据
	public String modAsset() {
		try {

			Asset a = this.getAssetService().get(asset.getId());
			String realPath = this.getRealPath("");
			// 修改单据图
			if (billFileName != null) {
				asset.setPicUrl2(FileHelper.saveFile(bill, billFileName,
						realPath));
			}
			// 删除部分图片
			String[] delPicUrls = this.delPic.split(",");
			for (String p : delPicUrls) {
				System.out.println(p.replaceAll("/", "\\\\"));
				FileHelper.deleteFile(realPath, p);
			}

			// 新增及修改图片
			if (picFileNames != null) {
				asset.setPicUrl1(asset.getPicUrl1() + ","
						+ FileHelper.saveFiles(pics, picFileNames, realPath));
			}
			// 计算 金额
			if (asset.getAstCount() > 1)
				asset.setAmount(asset.getPrice() * asset.getAstCount());
			else
				asset.setAmount(asset.getPrice());
			BeanUtils.copyProperties(asset, a);
			this.getAssetService().update(a);

			this.code = 0;
			this.msg = URLEncoder.encode("修改成功", "utf-8");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}
		if (stamp == 0)
			return "toResNotAduit";
		else if (stamp == 1)
			return "firstAduitCmplt";
		else
			return "lastAduitCmplt";
	}

	// 删除资产 type=1 跳转到登记管理 type=2跳转到初审
	public String delete() {

		try {
			this.assetService.delete(this.assetService.get(asset.getId()));
			this.code = 0;
			this.msg = URLEncoder.encode("删除成功", "utf-8");
			// 返根据参数返回不同的待审核界面
			if (this.type == null) {
				return "";
			}
			if (this.type.equals("1")) {
				return "toResNotAduit";
			} else if (this.type.equals("2")) {
				return "";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

	public String deleteAll() {
		Integer type = Integer.parseInt(this.getRequest().getParameter("type"));
		try {
			auditNoArray = this.getRequest().getParameter("auditNoArray");
			if (auditNoArray != null) {
				this.code = this.assetService.astDeleteAll(auditNoArray);
				this.msg = URLEncoder.encode("删除成功", "utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		if (type == 1)
			return "firstAduitCmplt";
		else
			return "toResNotAduit";
	}

	/**
	 * 未审数据查询
	 */
	public String findAstNotAduit() {
		try {
			chargeOffDeptList = this.getSysService().getChargeOffDept();
			if (this.msg != null) {
				this.msg = new String(msg.getBytes("iso8859-1"), "UTF-8");
			}
			asset = this.getAssetType("S");
			if (this.code == null) {
				this.code = -1;
			}
			String deptNo = this.getSessionAttr("user", User.class).getDeptNo()
					.trim();
			pagination = this.assetService.findAstByExample(pagination, asset,
					astRange, deptNo);
			pagination.setUrl("/swss" + this.getRequest().getServletPath());
			if (this.pagination.getRowcount() == 0)
				this.msg = "无满足条件的记录";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}
		return "resNotAduit";
	}

	// 初审数据查询
	@SuppressWarnings("unchecked")
	public String findAstFirstAduit() {
		String deptNo = this.getSessionAttr("user", User.class).getDeptNo()
				.trim();
		try {
			if (this.msg != null) {
				this.msg = new String(msg.getBytes("iso8859-1"), "UTF-8");
			}
			chargeOffDeptList = this.getSysService().getChargeOffDept();
			asset = this.getAssetType("S");
			if (this.pagination == null) {
				pagination = new Pagination();
			}
			pagination = this.assetService.findAstFirstByExample(pagination,
					asset, astRange, deptNo);
			pagination.setUrl("/swss" + this.getRequest().getServletPath());

			if (this.pagination.getRowcount() == 0)
				this.msg = "无满足条件的记录";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}

		return "resFirstAduit";
	}

	// 终审数据查询
	@SuppressWarnings("unchecked")
	public String findAstLastAduit() {
		try {
			String deptNo = this.getSessionAttr("user", User.class).getDeptNo().trim();
			chargeOffDeptList = this.getSysService().getChargeOffDept();
			if (this.msg != null) {
				this.msg = new String(msg.getBytes("iso8859-1"), "UTF-8");
			}
			asset = this.getAssetType("S");
			if (this.pagination == null) {
				pagination = new Pagination();
			}
			pagination = this.assetService.findAstLastByExample(pagination,asset,astRange,deptNo);
			pagination.setUrl("/swss" + this.getRequest().getServletPath());

			if (this.pagination.getRowcount() == 0)
				this.msg = "无满足条件的记录";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}
		return "resLastAduit";
	}

	// 通过初审 状态为3 进入财务审核 财务审核失败状态变为2 修改后变为3 继续财务审核
	public String goFirstAduit() {
		try {
			auditNoArray = this.getRequest().getParameter("auditNoArray");
			if (auditNoArray != null) {
				this.code = this.assetService.astFirstAuditUpdate(auditNoArray);
				this.msg = URLEncoder.encode("审核成功", "utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return "firstAduitCmplt";
	}

	// 初审退回 变为状态0 录入者修改成功后变为1 再次进入流程
	public String backFirstAduit() {
		return "firstAduitCmplt";
	}

	// 终审通过 状态为7
	public String goLastAduit() {
		try {
			auditNoArray = this.getRequest().getParameter("auditNoArray");
			if (auditNoArray != null) {
				this.code = this.assetService.astLastAuditUpdate(auditNoArray);
				this.msg = URLEncoder.encode("审核成功", "utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return "lastAduitCmplt";
	}

	// 终审退回页面初始化
	public String initBackaduit() {
		try {
			auditNoArray = this.getRequest().getParameter("auditNoArray");
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return "gobackaduit";
	}

	// 终审退回 状态为4
	public String backLastAduit() {
		try {
			String returreas = this.getRequest().getParameter("returreas");
			auditNoArray = this.getRequest().getParameter("auditNoArray");
			this.code = this.assetService.astLastAuditBack(auditNoArray,
					returreas);
			this.msg = URLEncoder.encode("退回成功", "utf-8");

		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return "lastAduitCmplt";
	}

	/**
	 * 输入EXCEL表格
	 * 
	 * @param exportType=1财务审核查询使用，2在账查询使用
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String down_excel() {
		try {
			Integer exportType = Integer.parseInt(this.getRequest().getParameter("exportType"));
			String deptNo = this.getSessionAttr("user", User.class).getDeptNo().trim();
			asset = this.getAssetType("S");
			if (pagination == null) {
				pagination = new Pagination();
			}
			pagination = this.assetService.findExcelExportByExample(pagination,asset, deptNo, exportType);
			// 生成excel文件(保存在服务器机上)
			Excel.writeAssetExcel(pagination.getResult(), 1);
			// 导出文件(下载到客户机上,并删除服务器机上的excel文件)
			Files.exportFile(this.getResponse(), true);

		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return null;
	}

	public String complexInit() {
		try {
			user = this.getSessionAttr("user", User.class);
			fundSubList = this.getSysService().getFundSub();
			financeUserList = this.getSysService().getFinanceUser(user.getFin().toString());
			chargeOffDeptList = this.getSysService().getChargeOffDept();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "complex";
	}

	// 高级查询
	// 资产在账查询
	public String findComplex() {
		try {
			String deptNo = this.getSessionAttr("user", User.class).getDeptNo().trim();
			AssetSearch as = this.getAssetSearchByType("S");
			pagination = this.assetService.findComplex(pagination, as.getAsset(), as.getAstRange(), deptNo, as.getHql());
			pagination.setUrl("/swss" + this.getRequest().getServletPath());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}
		return "resComplex";
	}

	/**
	 * 判断asset对象是否为条件查询或默认查询内容 对相关系统 设备，家具等设置标记 astmark S、Q等
	 * 
	 * @return
	 */
	public Asset getAssetType(String astType) {
		// clearbean=1 清空session
		if (this.clearbean != null && this.clearbean == 1) {
			this.setSessionAttr("searchBean", null);
		} else {
			if (asset != null) {
				this.setSessionAttr("searchBean", asset);
			} else {
				asset = this.getSessionAttr("searchBean", null);
			}
		}
		if (asset == null) {
			asset = new Asset();
			asset.setAstMark(astType);
		} else
			asset.setAstMark(astType);
		return asset;
	}
	/**高级
	 * 在账组合查询
	 * @param astType
	 * @return
	 */
	public AssetSearch getAssetSearchByType(String astType) {
		// clearbean=1 清空session
		AssetSearch as = null;
		if (this.clearbean != null && this.clearbean == 1) {
			as = new AssetSearch();
			as.setAsset(asset);
			as.setAstRange(astRange);
			as.setHql(hql);
			this.setSessionAttr("searchBean", null);
		} else {
			//有条件查询
			if (asset != null || hql != null || astRange != null) {
				as = this.getSessionAttr("searchBean", null);
				if (as == null) {
					as = new AssetSearch();
				}
				if (hql != null) {
					as.setAsset(null);
					as.setHql(hql);
					as.setAstRange(null);
				}
				if (astRange != null) {
					as.setAsset(null);
					as.setAstRange(astRange);
					as.setHql(null);
				}
				if (asset != null) {
					Asset ast = as.getAsset();
					if (ast == null) {
						ast = new Asset();
					} else {
						if ((ast.getDeptNo() != null)
								|| (ast.getFinAccount() != null)
								|| (ast.getFinDeptName() != null)) {
							ast = new Asset();
						}
					}
					BeanUtils.copyProperties(asset, ast);
					as.setAsset(ast);
				}
				this.setSessionAttr("searchBean", as);
			} else {
				as = this.getSessionAttr("searchBean", null);
			}
		}
		if (as == null) {
			as = new AssetSearch();
		}
		if (as.getAsset() == null) {
			Asset ast = new Asset();
			ast.setAstMark(astType);
			as.setAsset(ast);
		} else {
			as.getAsset().setAstMark(astType);
		}
		return as;
	}
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Pagination<?> getPagination() {
		return pagination;
	}

	public void setPagination(Pagination<?> pagination) {
		this.pagination = pagination;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public SysService getSysService() {
		return sysService;
	}

	public void setSysService(SysService sysService) {
		this.sysService = sysService;
	}

	public List<?> getFundSubList() {
		return fundSubList;
	}

	public void setFundSubList(List<?> fundSubList) {
		this.fundSubList = fundSubList;
	}

	public List<?> getUseDirList() {
		return useDirList;
	}

	public void setUseDirList(List<?> useDirList) {
		this.useDirList = useDirList;
	}

	public List<?> getNowStatusList() {
		return nowStatusList;
	}

	public void setNowStatusList(List<?> nowStatusList) {
		this.nowStatusList = nowStatusList;
	}

	public List<?> getAstSourceList() {
		return astSourceList;
	}

	public void setAstSourceList(List<?> astSourceList) {
		this.astSourceList = astSourceList;
	}

	public CurrentPeriodService getCurrentPeriodService() {
		return currentPeriodService;
	}

	public void setCurrentPeriodService(
			CurrentPeriodService currentPeriodService) {
		this.currentPeriodService = currentPeriodService;
	}

	public Asset getAsset() {
		return asset;
	}

	public void setAsset(Asset asset) {
		this.asset = asset;
	}

	public AssetService getAssetService() {
		return assetService;
	}

	public void setAssetService(AssetService assetService) {
		this.assetService = assetService;
	}

	public List<?> getChargeOffDeptList() {
		return chargeOffDeptList;
	}

	public void setChargeOffDeptList(List<?> chargeOffDeptList) {
		this.chargeOffDeptList = chargeOffDeptList;
	}

	public File[] getPic() {
		return pics;
	}

	public void setPic(File[] pic) {
		this.pics = pic;
	}

	public String[] getPicFileName() {
		return picFileNames;
	}

	public void setPicFileName(String[] picFileName) {
		this.picFileNames = picFileName;
	}

	public String[] getPicContentType() {
		return picContentTypes;
	}

	public void setPicContentType(String[] picContentType) {
		this.picContentTypes = picContentType;
	}

	public File getBill() {
		return bill;
	}

	public void setBill(File bill) {
		this.bill = bill;
	}

	public String getBillFileName() {
		return billFileName;
	}

	public void setBillFileName(String billFileName) {
		this.billFileName = billFileName;
	}

	public String getBillContentTypes() {
		return billContentTypes;
	}

	public void setBillContentTypes(String billContentTypes) {
		this.billContentTypes = billContentTypes;
	}

	public char getAstType() {
		return astType;
	}

	public void setAstType(char astType) {
		this.astType = astType;
	}

	public List<?> getAstList() {
		return astList;
	}

	public void setAstList(List<?> astList) {
		this.astList = astList;
	}

	public Integer getSearchType() {
		return searchType;
	}

	public void setSearchType(Integer searchType) {
		this.searchType = searchType;
	}

	public String getAuditNoArray() {
		return auditNoArray;
	}

	public void setAuditNoArray(String auditNoArray) {
		this.auditNoArray = auditNoArray;
	}

	public Integer getClearbean() {
		return clearbean;
	}

	public void setClearbean(Integer clearbean) {
		this.clearbean = clearbean;
	}

	public Integer getStamp() {
		return stamp;
	}

	public void setStamp(Integer stamp) {
		this.stamp = stamp;
	}

	public String getDelPic() {
		return delPic;
	}

	public void setDelPic(String delPic) {
		this.delPic = delPic;
	}

	public List<?> getByglList() {
		return byglList;
	}

	public void setByglList(List<?> byglList) {
		this.byglList = byglList;
	}

	public ByglService getGbyglService() {
		return gbyglService;
	}

	public void setGbyglService(ByglService gbyglService) {
		this.gbyglService = gbyglService;
	}

	public List<?> getZjfsList() {
		return zjfsList;
	}

	public void setZjfsList(List<?> zjfsList) {
		this.zjfsList = zjfsList;
	}

	public Integer getPrintType() {
		return printType;
	}

	public void setPrintType(Integer printType) {
		this.printType = printType;
	}

	public String getHql() {
		return hql;
	}

	public void setHql(String hql) {
		this.hql = hql;
	}

	public List<?> getFinanceUserList() {
		return financeUserList;
	}

	public void setFinanceUserList(List<?> financeUserList) {
		this.financeUserList = financeUserList;
	}

	public AstRange getAstRange() {
		return astRange;
	}

	public void setAstRange(AstRange astRange) {
		this.astRange = astRange;
	}
}
